package com.homepig.mongodb;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;

/**
 * 插入文档
 *
 * @author homepig
 * @version 1.0
 */
public class InsertDocuments {
    private static MongoCollection mongoCollection;

    static {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase mongoDatabase = mongoClient.getDatabase("mongo_stu");
        mongoCollection = mongoDatabase.getCollection("inventory");
        mongoCollection.drop();
    }

    /**
     * 插入一个文档<br>
     * 注：如果集合不存在，执行插入操作时会先创建集合;<br>
     * 如果没有指定_id字段，那么驱动程序会自动将带有ObjectId值的_id字段插入到文档中。
     */
    public void insertASingleDocument() {
        Document heros = new Document("country", "america");
        heros.append("sex", "man").append("crew", singletonList("Captain America"));

        Document look = new Document();
        look.append("name", "america").append("height", "220cm");
        look.append("weight", "100kg");

        heros.put("look", look);
        mongoCollection.insertOne(heros);
    }

    /**
     * 插入多个文档<br>
     */
    public void insertMultipleDocument() {
        Document captainAmerica = new Document("height", "220cm").append("weight", "100kg").append("name", "captainAmerica");
        Document ironMan = new Document("height", "200cm").append("weight", "99kg").append("name", "ironMan");

        mongoCollection.insertMany(asList(captainAmerica, ironMan));
    }

    public static void main(String[] args) {
        InsertDocuments insertDocuments = new InsertDocuments();
        insertDocuments.insertASingleDocument();
        insertDocuments.insertMultipleDocument();
    }
}
